<template>
  <div class="home-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">角色列表</a></el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="form-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入"
            v-model="queryInfo.query"
            clearable
            @clear="getRoleList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getRoleList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="roleList"
        style="width: 100%; margin-top: 20px"
        border
        stripe
      >
        <el-table-column type="expand" class="children-box">
          <template slot-scope="scope">
            <div style="padding: 20px">
              <el-row
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
                :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag key="item1.rightName" closable>
                    {{ item1.rightName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <el-row
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  >
                    <!--渲染二级权限  -->
                    <el-col :span="5">
                      <el-tag key="item2.rightName" closable type="success">
                        {{ item2.rightName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="19">
                      <!-- 渲染三级权限 -->

                      <el-col>
                        <el-tag
                          v-for="item3 in item2.children"
                          :key="item3.rightName"
                          closable
                          type="warning"
                        >
                          {{ item3.rightName }}
                        </el-tag>
                      </el-col>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="序号" width="100" align="center">
          <template slot-scope="scope">{{
            scope.$index + 1 + queryInfo.num * (queryInfo.page - 1)
          }}</template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="comment" label="角色描述"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="120">
          <template slot-scope="scope">
            {{ scope.row.createTime | DateFormat }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <!-- 查看角色用户 -->
            <el-tooltip
              effect="dark"
              content="查看角色用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-s-custom"
                @click="openRoleUser(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="openSetRight(scope.row)"
              >
              </el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="confirm_del(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.page"
        :page-size="queryInfo.num"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="rightDialog" width="50%">
      <el-tree
        :data="rightList"
        show-checkbox
        ref="tree"
        node-key="id"
        :default-checked-keys="defaultKey"
        default-expand-all
        :props="defaultProps"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitRightForm('addFormref')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 查看角色用户 -->
    <el-dialog title="查看角色用户" :visible.sync="userRoleDialog" width="50%">
      <el-table :data="userRoleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChangeUserRole"
        @current-change="handleCurrentChangUserRolee"
        :current-page.sync="userRole.page"
        :page-size="userRole.num"
        layout="total, prev, pager, next"
        :total="userRole.total"
      >
      </el-pagination>
    </el-dialog>

    <!-- 添加角色 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%">
      <!-- 内容主体区域 -->
      <el-form
        label-width="80px"
        :rules="addRoleFormRule"
        ref="addRoleForm"
        :model="addRoleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input type="textarea" v-model="addRoleForm.comment"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRoleForm('addRoleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      queryInfo: {
        query: '',
        num: 10,
        page: 1
      },
      roleList: [],
      total: 0,
      rightDialog: false,
      rightList: [],
      roleId: 0,
      defaultProps: {
        label: 'rightName',
        children: 'children'
      },
      // 默认选中的树节点
      defaultKey: [],
      userRoleList: [],
      userRoleDialog: false,
      userRole: {
        page: 1,
        num: 10,
        total: 0,
        id: 0
      },
      addRoleForm: {
        roleName: '',
        comment: ''
      },
      dialogVisible: false,
      addRoleFormRule: {
        roleName: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }
        ]
      }
    }
  },
  created () {
    this.getRoleList()
    this.getRight()
  },
  computed: {},
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.post(
        '/role/getRoleByPage',
        this.queryInfo
      )
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.roleList = res.data
      this.total = res.count
    },
    open_editForm (id) {
      console.log(id)
    },
    confirm_del (id) {
      this.$confirm('是否确认删除角色信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.post('/role/delRole', {
            id: id
          })
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.$message.success('删除成功！')
          this.getRoleList()
        })
        .catch(() => {})
    },
    handleSizeChange (val) {
      this.queryInfo.num = val
      this.getRoleList()
    },
    handleCurrentChange (val) {
      this.queryInfo.page = val
    },
    handleSizeChangeUserRole (val) {
      this.UserRole.num = val
      this.getRoleList()
    },
    handleCurrentChangUserRolee (val) {
      this.UserRole.page = val
      this.getRoleList()
    },
    openSetRight (obj) {
      this.rightDialog = true
      this.roleId = obj.id
      this.getRoleDetail(this.roleId)
    },
    async getRoleDetail (id) {
      const { data: res } = await this.$http.post('/role/getRoleDetail', {
        id: id
      })
      if (res.code !== 200) return res.cc(res.msg)
      // 清空
      this.$refs.tree.setCheckedKeys([])
      this.defaultKey = res.data
    },
    async submitRightForm () {
      const rights = this.$refs.tree.getCheckedKeys().join(',')
      const { data: res } = await this.$http.post('/right/Auth2Role', {
        rights: rights,
        roleId: this.roleId
      })
      if (res.code !== 200) return this.$message.error(res.msg)
      this.$message.success('修改权限成功！')
      this.rightDialog = false
      this.getRoleList()
    },
    async getRight () {
      const { data: res } = await this.$http.post('/right/all')
      if (res.code !== 200) return this.$message.error(res.code)
      this.rightList = res.data
    },
    async getuserRole (id) {
      this.userRole.id = id
      const { data: res } = await this.$http.post(
        '/role/getUserRole',
        this.userRole
      )
      if (res.code !== 200) return this.$message.error(res.msg)
      this.userRoleList = res.data
      this.userRole.total = res.total
    },
    openRoleUser (id) {
      this.userRoleDialog = true
      this.getuserRole(id)
    },
    openRoleDialog () {
      this.dialogVisible = true
      this.$refs.addRoleForm.resetFields()
    },
    submitAddRoleForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const {
            data: res
          } = await this.$http.post('/role/addRole', this.addRoleForm)
          if (res.code !== 200) {
            this.$message.error(res.msg)
            this.dialogVisible = false
            return false
          }
          this.$message.success('添加角色成功！')
          this.dialogVisible = false
          this.getRoleList()
        } else {
          this.$message.error('添加角色失败！')
          this.dialogVisible = false
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.form-container {
  margin-top: 20px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  line-height: 50px;
  // .el-col {
  //   text-align: center;
  // }
  i {
    cursor: pointer;
  }
}
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
